package com.aaron.android.battery;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.util.Log;

public class UpgradeHelper {

	private final static String TAG = "UpgradeHelper";
	
	private int serverVersionCode = 0;
	private String serverVersionName = "";

	public int getServerVersionCode() {
		return serverVersionCode;
	}

	public String getServerVersionName() {
		return serverVersionName;
	}

	public boolean fetchServerVersion() {
		try {
			String verjson = getContent(AppConfig.UPGRADE_HOST
					+ AppConfig.UPGRADE_VERSION_FILE);
			JSONObject obj = new JSONObject(verjson);
			if (obj != null) {
				try {
					serverVersionCode = Integer.parseInt(obj
							.getString("versionCode"));
					serverVersionName = obj.getString("versionName");
				} catch (Exception e) {
					serverVersionCode = -1;
					serverVersionName = "";
					return false;
				}
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
			return false;
		}

		return true;
	}

	private static String getContent(final String url) throws Exception {

		Log.d(TAG, url);

		StringBuilder sb = new StringBuilder();

		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpResponse response = client.execute(new HttpGet(url));
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"), 8192);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();
		}
		return sb.toString();
	}

}